var detail = new Vue({
    el: '#app',
    data() {
        var date = this.format('yyyy-mm-dd');
        var d = new Date();
        var year = d.getFullYear();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return {
            id: 0,
            info: {},
            order: {
                push: [],
                date: date,
                hour: 1,
            },
            timeText:"",
            times:[],
            selectTimes:[],
            selectPopup:false,
            year:year,
            month: month,
            day: day,
            week:"",
            weeks:weeks,
            timesTemp:[]
        }
    },
    mounted() {
            this.id = this.GetQueryString('id')?this.GetQueryString('id'):0;
            if(this.GetQueryString('year')){
                this.year = this.GetQueryString('year')
            }
            if(this.GetQueryString('month')){
                this.month = this.GetQueryString('month')
            }
            if(this.GetQueryString('day')){
                this.day = this.GetQueryString('day')
            }
            var d = new Date(this.year+'/'+this.month+'/'+this.day);
            this.order.date=this.format('yyyy-mm-dd',d);
            this.week=d.getDay();
            this.getRoomInfo()
    },
    watch: {
        times:{
            handler(newVal,oldVal){
                if(newVal.length==0){
                    this.timeText= "";
                }
                if(newVal.length==1){
                    this.timeText=this.format("hh:ii开始",newVal[0]);
                }
                if(newVal.length==2){
                    var end=newVal[1].setMinutes(newVal[1].getMinutes() + 15);
                    this.timeText=this.format("hh:ii开始",newVal[0])+this.format("hh:ii前结束",new Date(end));
                }
            },
            deep:true
        },
        selectTimesChange:{
            handler(newVal,oldVal){
                if(newVal.length==0){
                    this.getRoomInfo();
                }
                if(newVal.length==1){
                    if(oldVal[0]){
                        this.info.times[oldVal[0].hour][oldVal[0].step]=true;
                    }
                    this.info.times[newVal[0].hour][newVal[0].step]=false;
                }
                if(newVal.length==2){
                    var setStatus=function(data,status,self){
                        for(var i in self.info.times){
                            for(var step in self.info.times[i]){
                                var start=data[0].hour*60+data[0].step*15
                                var end=data[1].hour*60+data[1].step*15
                                var time=i*60+step*15;
                                if(time>=start&&time<=end){
                                    self.$set(self.info.times[i],step,status)
                                }
                            }
                        }
                    }
                    // 将旧选择数据改为开启状态
                    if(oldVal[0]&&!oldVal[1]){
                        this.info.times[oldVal[0].hour][oldVal[0].step]=true;
                    }else{
                        setStatus(oldVal,true,this);
                    }
                    // 修改为关闭状态
                    setStatus(newVal,false,this);
                }
            },
            deep:true
        }
    },
    computed: {
        selectTimesChange() {
          return JSON.parse(JSON.stringify(this.selectTimes))
        }
    },
    updated:function(){
        var swiper = new Swiper('.swiper-container', {
          slidesPerView: 7,
          spaceBetween: 15,
          freeMode: true,
          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
          }
        });
    },
    methods: {
        onTimeClick(isOpen,hour,step){
            // 关闭状态
            var minutes=[0,15,30,45];
            var _hour=hour>9?hour:'0'+hour;
            var date=new Date(this.order.date.replace(/\-/g, "/")+' '+_hour+':'+minutes[step]+':00');
            if(!this.times[0]||(this.times[0]&&date<this.times[0])){
                this.$set(this.times,0, date)
                this.$set(this.selectTimes,0, {hour:hour,step:step});
            }else{
                this.$set(this.times,1, date)
                this.$set(this.selectTimes,1, {hour:hour,step:step});
            }
        },
        cancel(){
            this.times=[];
            this.selectTimes=[];
            this.getRoomInfo();
        },
        GetQueryString(name){
             var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
             var r = window.location.search.substr(1).match(reg);//search,查询？后面的参数，并匹配正则
             if(r!=null)return  unescape(r[2]); return null;
        },
        getRoomInfo() {
            var params = {}
            params.id = this.id
            params.day = this.day
            params.month = this.month
            params.year = this.year
            var _this = this;
            _this.$indicator.open('加载中...');
            axios.get(root + '/api/info', { params: params }).then(function(res) {
                if (res.status == 200 && res.data.code == 1) {
                    _this.info = res.data.data
                    _this.timesTemp==res.data.data.times;
                    _this.$indicator.close();
                } else {
                    _this.$indicator.close();
                }
            }).catch(function(error) {
                console.error(error)
                _this.$indicator.close();
            })
        },
        openPicker() {
            this.cancel();
            this.$refs.picker.open();
        },
        selectDate(date) {
            this.order.date = this.format('yyyy-mm-dd', date);
            this.year = date.getFullYear();
            this.month = date.getMonth() + 1;
            this.day = date.getDate();
            this.week=date.getDay();
            this.getRoomInfo();
        },
        format(format, date) {
            if (!date) {
                date = new Date();
            }
            var o = {
                "m+": date.getMonth() + 1, //month
                "d+": date.getDate(), //day
                "h+": date.getHours(), //hour
                "i+": date.getMinutes(), //minute
                "s+": date.getSeconds(), //second
                "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
                "S": date.getMilliseconds() //millisecond
            }
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                }
            }
            return format;
        },
        post() {
            if (!this.order.title) {
                this.$toast('请输入会议主题');
                return false;
            }
            if (!this.order.date) {
                this.$toast('请输入会议日期');
                return false;
            }
            if(!this.times[0]||!this.times[1]){
                this.$toast('请选择会议时间');
                return false;
            }
            if(!this.order.people){
                this.$toast('请输入参会人数');
                return false;                
            }
            if (!this.order.hour) {
                this.$toast('会议时长不能为空');
                return false;
            }
            if(this.order.people>this.info.people){
                this.$toast('超过房间最大容纳人数');
                return false;
            }
            var params = new URLSearchParams();
            params.append('room_id', this.info.id);
            params.append('title', this.order.title);
            params.append('date', this.format("yyyy-mm-dd hh:ii:ss",this.times[0]));

            params.append('people', this.order.people);
            params.append('contact', this.order.contact);
            params.append('token', token);
            var dateDiff = this.times[1].getTime() - this.times[0].getTime();//时间差的毫秒数
            var hours=dateDiff/(3600*1000)//计算出小时数
            params.append('hour', hours);

            var _this = this;
            axios.post(root + '/api/orderCreate', params).then(function(res) {
                if (res.status == 200) {
                    if(res.data.code == 1){
                        _this.$messagebox.alert('提交成功').then(function(){
                            window.location.href=root+'/meeting.html'
                        })
                    }else if(res.data.code == -1){
                        _this.$toast(res.data.msg);
                        // 时段被占用，重新刷新数据
                        _this.times=[];
                        _this.selectTimes=[];
                        _this.getRoomInfo();
                    }else{
                        _this.$toast(res.data.msg);
                    }
                } else {
                    _this.$toast('提交失败');
                }
            })
        },
        select(){
            var _this=this;
            if(_this.users.length>1){
                _this.selectPopup=true;
                return false;
            }
            _this.$indicator.open('获取中...');
            axios.get(root + '/wechat/users').then(function(res) {
                if (res.status == 200 && res.data.code == 1) {
                    var users=[];
                    for(var i in res.data.data){
                        users.push({
                            label:res.data.data[i].name,
                            value:res.data.data[i].userid
                        })
                    }
                    _this.users=users;
                    _this.$indicator.close();
                    _this.selectPopup=true;
                } else {
                    _this.$indicator.close();
                }
            }).catch(function(error) {
                console.error(error)
                _this.$indicator.close();
            })
        },
        selectClose(){
            this.selectPopup=false;
            this.order.people=this.order.users.length;
        }
    }

})